<template>
  <a-modal
    :visible="visible"
    title="选择费用类型"
    :width="540"
    @ok="handleOk"
    @cancel="closeModal"
  >
    <div class="ant-cascader-select">
      <div class="content-item-right">
        <div class="select-content">
          <div v-for="(item,index) in selectedValueArr" :key="index" class="tags-box">
            <div class="select-tag" :class="readDeleteTagKey === item.value ? 'err-tag' : 'default-tag'">
              {{item.label}}
              <span class="select-tag-del" @click="delSelect(item.value)">
              <cu-icon class="icon" type="org-chahao"></cu-icon>
            </span>
            </div>
          </div>
          <div class="input-box">
            <a-input
              class="input-tag"
              v-model:value="searchValue"
              placeholder="请搜索费用类型"
              @change="goSearch"
              @keydown="searchKeyDown"
              v-codeFocus
            />
          </div>
        </div>
        <div class="clear-all" v-if="selectedValueArr.length || searchValue">
          <cu-icon class="clear-all-icon" type="org-qingchu"  @click.stop="clearAll"></cu-icon>
        </div>
      </div>

      <div class="ant-cascader-select-drop">
        <div class="ant-select-dropdown-content">
          <a-col class="type-col" v-if="!searchValue">
            <a-list size="small" :data-source="treeDataList" :split="false" class="list-select">
              <template #renderItem="{ item, index }">
                <a-list-item
                  @click="() => handleClick(item, index)"
                  :class="{active: activeIdx === index }"
                  class="list-box"
                >
                  <span class="list-box-name">{{ item[optionName] }}</span>
                  <cu-icon class="icon" type="org-xiangyou1" />
                </a-list-item>
              </template>
            </a-list>
          </a-col>
          <!-- cascader-child -->
          <a-col :class=" searchValue ? 'list-col' : 'list-col border-left'">
            <a-list size="small" :data-source="searchValue ? filterList : childList" :split="false" class="list-select">
              <template #renderItem="{ item, index }">
                <a-list-item @click="() => handleClick(item, index)" class="list-box">
                  <a-checkbox :checked="getChecked(item)"></a-checkbox>
                  <span class="list-box-name">{{ item[optionName] }}</span>
                </a-list-item>
              </template>
            </a-list>
          </a-col>
        </div>
      </div>

    </div>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
} from "vue";
import request from "../../common/utils/request";
import _ from "lodash";

export default defineComponent({
  name: "SelectCostType",
  components: { },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    value: {
      type: Array,
      default: () => {
        return [];
      }
    },
    disabledBond: {
      type: Boolean,
      default: false,
    }
  },

  setup(props, { emit }) {
    const state = reactive({
      treeDataList: [], // 数据
      activeIdx: 0,
      selectedValueArr: [], // 选择的数据
      searchValue: '', // 搜索
      filterList: [], // 搜索结果
      readDeleteTagKey: '', // 待删除
    });

    const optionValue = computed(() => {return props?.optionFilterProp || 'value'});
    const optionName = computed(() => {return props?.optionLabelProp || 'label'});
    const childList = computed(() => {return state.treeDataList[state.activeIdx]?.children || []});

    const getChildren = (targetOption) => {
      targetOption.loading = true;
      return new Promise((resolve, reject) => {
        request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption[optionValue.value],
            status: 1,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                level: 1,
              }));
            }
            resolve(res)
          });
      })
    };

    const handleClick = async (option, index) => {
      const val = option[optionValue.value];
      if (!option.level) {
        await getChildren(option);
      }
      if (!option.level) {
        // 第一层级 ( 不可选择的层级 )
        state.activeIdx = index
      } else {
        // change the model's data
        if (state.selectedValueArr.find((v) => v[optionValue.value] === val)) {
          let curIdx = state.selectedValueArr.findIndex((item) => {
            return val === item[optionValue.value]
          })
          state.selectedValueArr.splice(curIdx, 1)
        } else {
          state.selectedValueArr.push(option)
        }
      }
    };

    const getChecked = (item) => {
      return !!state.selectedValueArr.find((v) => v[optionValue.value] === item[optionValue.value]);
    };

    // 搜索
    let timeout = null;
    let currentValue = "";
    const getSearchList = (value) => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      currentValue = value;
      // 搜素请求
      const searchList = () => {
        let params = {
          page: 1, limit: 9999,keyword: value
        }
        if (props.disabledBond) {
          params.is_bond = 0
        }
        request
          .get("/org", "/bill/costList",  params)
          .then((res) => {
            if (currentValue === value) {
              state.filterList = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                level: 1,
              }));
            }
          });
      };
      timeout = setTimeout(searchList, 1000);
    }

    const goSearch = () => {
      state.searchValue = state.searchValue.trim();
      state.filterList = [];
      if (state.searchValue) {
        getSearchList(state.searchValue);
      }
    };

    const handleOk = () => {
      emit('costConfirm', state.selectedValueArr);
    };

    const closeModal = () => {
      emit('closeModal')
    }

    const delSelect = (value) => {
      let curIdx = state.selectedValueArr.findIndex((item) => {
        return value === item[optionValue.value]
      })
      state.selectedValueArr.splice(curIdx, 1)
    }

    const searchKeyDown = (e) => {
      if (!state.searchValue) {
        if (e.keyCode === 8 && state.selectedValueArr.length) {
          // 判断是否有准备删除的数据 // 如果有 删除那条tag 没有的话 准备删除最后一条数据
          if (state.readDeleteTagKey) {
            delSelect(state.readDeleteTagKey);
            state.readDeleteTagKey = '';
          } else {
            state.readDeleteTagKey = state.selectedValueArr[state.selectedValueArr.length-1].value;
          }
        }
      }
    }

    const reset = () => {
      state.treeDataList = [];
      state.activeIdx = 0;
      state.selectedValueArr = [];
      state.searchValue = '';
      state.filterList = [];
      state.readDeleteTagKey = '';
    };

    const clearAll = () => {
      state.selectedValueArr = [];
      state.searchValue = '';
    };

    const init = () => {
      state.selectedValueArr = _.cloneDeep(props.value);
      let params = {};
      if (props.disabledBond) {
        params.is_bond = 0
      }
      request.get("/org", "/bill/cost/categoryList", params).then((res) => {
        if (res.list) {
          state.treeDataList = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            level: 0,
          }));
          if (state.treeDataList?.length) {
            getChildren(state.treeDataList[0]);
          }
        }
      });
    }

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );


    return {
      ...toRefs(state),
      closeModal,
      handleOk,
      childList,
      optionValue,
      optionName,
      ...toRefs(state),
      handleClick,
      getChecked,
      goSearch,
      searchKeyDown,
      delSelect,
      clearAll,
    };
  },
  directives: {
    codeFocus: {
      mounted(el, binding, vnode) {
        let parent = el.parentNode.parentNode.parentNode
        el.onfocus = function () {
          parent.className = 'content-item-right special_input_focus'
        }
        el.onblur = function () {
          parent.className = 'content-item-right'
        }
      }
    },
  }
});
</script>

<style lang="less" scoped>
.list-box {
  display: flex;
  .list-box-name {
    display: inline-block;
    flex: 1;
    word-break: break-all;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}
:deep(.ant-select-dropdown-content) {
  width: 100% !important;
  display:flex !important;
  margin-top: 16px;
  .type-col {
    min-width: 120px;
    max-width: 180px;
  }
  .list-col {
    flex: 1;
    min-width: 220px;
  }
  .border-left {
    border-left: 1px solid #e8e8e8;
  }
}
:deep(.ant-list-something-after-last-item .ant-spin-container > .ant-list-items > .ant-list-item:last-child) {
  border-bottom: none;
}

:deep(.ant-select-dropdown-content .ant-col:last-child li .ant-checkbox-wrapper) {
  margin-right: 12px;
}

:deep(.ant-select-dropdown-content .ant-col:last-child li) {
  justify-content: flex-start;
}
:deep(.ant-list-items .ant-list-item) {
  padding-left:12px;
  padding-right:12px;
  cursor: pointer;
}
:deep(.ant-list-items .ant-list-item > span) {
  white-space: nowrap;
}
:deep(.ant-list-footer .ant-tag) {
  margin-left: 12px;
  cursor: pointer;
}

.ant-list-footer .ant-input + .ant-input-suffix{
  margin-right: 6px;
}
.ant-list-footer .ant-input + .ant-input-suffix i{
  color: #1890ff;
}
.ant-list-items .ant-list-item:hover, .ant-cascader-select-drop .ant-list-items .ant-list-item.active {
  color: #1890ff;
}

.ant-list-items .ant-list-item:hover i, .ant-cascader-select-drop .ant-list-items .ant-list-item.active i{
  color: #1890ff;
}
.ant-list-items .ant-list-item i{
  font-size: 10px;
  color: #7d8292;
  margin-left: 6px;
}
.list-select {
  max-height: 240px;
  overflow-y: auto;
}

.content-item-right {
  display: flex;
  background: #fff;
  padding: 2px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  &:hover {
    border-color: #40a9ff;
    outline: 0;
    box-shadow: 0 0 0 2px #1890ff33;
  }
}
.tags-box {
  display: flex;
}

.select-tag {
  height: 24px;
  line-height: 24px;
  margin-bottom: 3px;
  margin-top: 3px;
  margin-right: 6px;
  border: none;
  border-radius: 4px;
  padding: 0 20px 0 6px;
  width: fit-content;
  max-width: 200px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  position: relative;
}
.select-tag-del {
  font-size: 11px;
  cursor: pointer;
  position: absolute;
  top: 0;
  right: 6px;
}
.default-tag {
  background-color: #e8e9e9;
  &:hover {
    background-color: #ddddde;
  }
}
.default-del-tag {
  background-color: #e0e9ff;
}
.err-del-tag {
  background-color: #e22f29;
  color: #fff;
}
.err-tag {
  background-color: #fee3e2;
  color: #e22f29;
  &:hover {
    background-color: #fcc5c3;
  }
}
.input-box {
  flex: 1;
  :deep(.ant-input) {
    padding-left: 0;
    &:focus {
      box-shadow: none!important;
    }
  }
}
.input-tag {
  max-width: 350px;
  min-width: 80px;
  border: none;
}

.special_input_focus {
  border-color: #40a9ff;
  outline: 0;
  box-shadow: 0 0 0 2px #1890ff33;
}

.select-content {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}
.clear-all {
  width: 20px;
  height: inherit;
  display: flex;
  justify-content: center;
  align-items: center;
}
.clear-all-icon {
  color: #bebebe;
  cursor: pointer;
  &:hover {
    color: #8c8c8c;
  }
}
</style>
